import BreadcrumbDept from '@/components/BreadcrumbDept';
import { getBatchNo } from "@/services/common/api";
import { getCategoryListByPage } from '@/services/stock-goods/api';
import { goodsListByPage, specListByGoodsId, stockRequestReturn, stockRequestStorage } from '@/services/stock-goods/subApi';
import { showMsg } from "@/utils/utils";
import ProForm, { ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable, { ProColumns } from "@ant-design/pro-table";
import { Button, Card, Col, Input, Row } from "antd";
import React, { useEffect, useRef, useState } from 'react';
import { history, useLocation, useModel } from "umi";
import './requestForm.less';

const RequestForm: React.FC = props => {

  const { state: locState } = useLocation<any>();

  const { initialState } = useModel('@@initialState');
  const { dept_code, dept_name } = initialState?.currentUser || {};

  const reqFormRef = useRef<ProFormInstance>();
  // 分类列表
  const [classList, setClassList] = useState<COMMON.SelectOption[]>([]);
  // 商品列表
  const [goodsList, setGoodsList] = useState<COMMON.SelectOption[]>([]);
  const [requestType, setRequestType] = useState<'R' | 'S'>('R');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const initColumns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '商品分类',
      dataIndex: 'class_name',
      colSize: 4,
      renderFormItem: (_, __, form) => (
        <ProFormSelect placeholder="选择商品分类" options={classList as any} showSearch
          fieldProps={{
            labelInValue: true,
            onChange: (_, option) => {
              form.resetFields(['goods_name']);
              if (!option) {
                form.submit();
              }
            }
          }}
        />
      )
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      colSize: 4,
      renderFormItem: (_, __, form) => {
        const class_id = form.getFieldValue('class_name')?.value;
        return (
          <ProFormSelect placeholder="选择商品" showSearch
            options={goodsList.filter((r: any) => r.class_id === class_id) as any}
            fieldProps={{
              labelInValue: true,
              onChange: (_, option) => {
                if (!option) {
                  form.submit();
                }
              }
            }}
          />
        );
      }
    },
    {
      title: '商品编号',
      renderText: (_, r) => r.goods_id,
      colSize: 3,
      renderFormItem: (_, __, form) => (<Input style={{ height: 24 }} value={form.getFieldValue('goods_name')?.value} readOnly={true} />)
    },
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      search: false
    }
  ];
  const [columns, setColumns] = useState<ProColumns<STOCKGOODSAPI.GoodsItem>[]>();

  useEffect(() => {
    getCategoryListByPage({ current: 1, pageSize: 9999 }).then((res: STOCKGOODSAPI.CategoryItemList) => {
      const list = res.record_list?.map(({ class_id, class_name }: any) => ({ value: class_id, label: class_name })) || [];
      setClassList(list);
    });
    goodsListByPage({ current: 1, pageSize: 9999 }).then(res => {
      const list = res.record_list.map(({ brand_name, goods_id, goods_name, goods_py, class_id }) => ({
        label: `【${brand_name}】${goods_name}（${goods_py}）`,
        value: goods_id,
        title: `【${brand_name}】${goods_name}`,
        class_id: class_id,
        goods_name: goods_name
      }));
      setGoodsList(list);
    });
  }, []);

  /**
   *  获取批次号
   */
  const fetchBatchNo = async () => {
    try {
      // 批次号
      const data = await getBatchNo();
      reqFormRef.current?.setFieldsValue({ 'batch_id': data.jrn_no });
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    }
  };

  /**
   * 提交申请
   * @param formData
   */
  const submitRequest = async (formData: STOCKGOODSAPI.BatchItem) => {
    if (selectedRowKeys.length === 0) {
      showMsg('请选择需要申请的商品规格');
      return;
    }
    let req: Promise<any>;
    if (requestType === 'S') {
      req = stockRequestReturn({ specs_id: selectedRowKeys[0], ...formData, inventory: -(formData.inventory ?? 0) });
    } else {
      req = stockRequestStorage({ specs_id: selectedRowKeys[0], ...formData });
    }
    req.then(res => {
      showMsg('申请已提交', 'success');
      history.push('/stock-goods/stock', { ...locState });
    }).catch(res => {
      showMsg(res?.data?.errmsg);
    });
  };

  return <>
    <PageContainer
      title="申请库存"
      breadcrumb={{}}
      extra={<BreadcrumbDept />}
      onBack={() => history.push('/stock-goods/stock', { ...locState })}
    >
      <Card className="main-content" bodyStyle={{ padding: '12px 0' }}>
        <Card title="1.选择商品规格" bordered={false}>
          <ProTable<STOCKGOODSAPI.GoodsItem>
            rowKey="specs_id"
            columns={columns ?? initColumns}
            options={false}
            manualRequest={true}
            cardProps={{ bodyStyle: { padding: '0' } }}
            pagination={{ showQuickJumper: true }}
            bordered
            search={{
              span: 2,
              labelWidth: 'auto',
              collapsed: false,
              optionRender: (config, props, [, queryBtn]) => [
                <Button type='primary' disabled={!config.form?.getFieldValue('goods_name')} onClick={() => config.form?.submit()}>
                  {config.searchText}
                </Button>
              ]
            }}
            request={async ({ goods_name, class_name, ...params }) => {
              try {
                const res = await specListByGoodsId({ ...params, goods_id: goods_name.value });
                // columns.push({
                //   title: 'abc',
                //   dataIndex: 'ab',
                //   isSpec: true
                // } as any)
                const data = res?.record_list ?? [];
                console.info(data);
                const refColumns = initColumns.concat(Object.keys(data[0]?.template_value ?? {}).map(key => ({ title: key, dataIndex: key, search: false, isSpec: true })));
                setColumns(refColumns);
                data.forEach(elem => {
                  elem['class_name'] = class_name.label;
                  elem['goods_name'] = goods_name.goods_name;
                  const tmpVal = elem.template_value ?? {};
                  Object.keys(tmpVal).forEach(key => elem[key] = tmpVal[key]);
                });
                return { success: true, data };
              } catch (error: any) {
                showMsg(error?.data?.errmsg);
                return { success: false, data: [] };
              }
            }}
            rowSelection={{
              type: "radio",
              onChange: setSelectedRowKeys
            }}
          />
        </Card>
        <Card title="2.申请库存" bordered={false}>
          <ProForm<STOCKGOODSAPI.BatchItem>
            formRef={reqFormRef}
            layout="horizontal"
            onFinish={submitRequest}
            submitter={{
              searchConfig: { submitText: '提交审核' },
              render: (_, [, submit]) => <div style={{ textAlign: 'center' }}>{submit}</div>
            }}
          >
            <ProFormRadio.Group
              label="申请方式" name="requestType" required
              labelCol={{ flex: '0 0 81px' }}
              options={[
                { label: '入库', value: 'R' },
                { label: '退回', value: 'S' }
              ]}
              fieldProps={{ defaultValue: 'R', onChange: e => setRequestType(e.target.value) }}
            />
            <Row gutter={32}>
              <Col span={12}>
                <ProFormText
                  name="batch_id" label="批次编号" placeholder='' fieldProps={{ readOnly: true }}
                  labelCol={{ flex: '0 0 80px' }} required rules={[{ required: true }]}
                  addonAfter={<Button type="primary" onClick={fetchBatchNo}>生成批次号</Button>}
                />
              </Col>
              <Col span={12}>
                <ProFormDigit name="inventory"
                  label={`${requestType === 'R' ? '入库' : '退回'}数量`} labelCol={{ flex: '0 0 80px' }}
                  fieldProps={{ precision: 0 }} min={1} max={999999} rules={[{ required: true }]}
                />
              </Col>
            </Row>
            <ProFormText name="explains"
              label={`${requestType === 'R' ? '入库' : '退回'}说明`}
              labelCol={{ flex: '0 0 80px' }}
            />
            <ProFormText name="batch_level" initialValue={2} hidden readonly />
            <ProFormText name="sub_dept_code" initialValue={dept_code} hidden readonly />
            <ProFormText name="sub_dept_name" initialValue={dept_name} hidden readonly />
          </ProForm>
        </Card>
      </Card>
    </PageContainer>
  </>;
};

export default RequestForm;
